package com.example.xinwenkehuduan;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpUtil {
    /**
     * 连接网络
     */
    public String connectServer() throws IOException {
        String url ="http://v.juhe.cn/toutiao/index?&key=fc7a909af12a357e6fcad68f91c79d1f";
        //获取网络连接对象
        OkHttpClient client = new OkHttpClient();
        //获取请求体
        RequestBody body = new FormBody.Builder().build();
        //获取请求
        Request request = new Request.Builder().post(body).url(url).build();
        //发送请求，获取服务器返回响应 注意：此方法必须执行在子线程
        Response response = client.newCall(request).execute();
        if(response.isSuccessful()){
            //获取响应中的数据，并转成string
            String data =response.body().string();
            return data;
        }else {
            throw new IllegalArgumentException("网络开小差，请检查您的网络。。。");
        }
    }
}
